import Taro from "@tarojs/taro";
import { getRechargePackageList, getRecorderDetail, payRechargePackage } from '@/services/payment';
import { sleep } from "@/utils";


const checkOrderStatus = async (id: string) => {
    let retryNum = 0;
    while (true) {
        await sleep(2000);
        const res = await getRecorderDetail({ id });
        if (res.success) {
            if (res.data.data.status === 4) {
                return true;
            }
        }
        retryNum++;
        if (retryNum > 10) {
            return false;
        }
    }
}

export const payHandler = async (orderid: string, payData: any) => {
    try {
        const payRes = await Taro.requestPayment({
            timeStamp: payData.time_stamp,
            nonceStr: payData.nonce_str,
            package: `prepay_id=${payData.prepay_id}`,
            signType: payData.sign_type,
            paySign: payData.pay_sign,
        });
        if (payRes.errMsg === 'requestPayment:ok') {
            // 轮训查询订单状态
            const result = await checkOrderStatus(orderid);
            if (result) {
                Taro.showToast({
                    title: '充值成功',
                    icon: 'success',
                });
                await sleep(1000);
                return {
                    success: true,
                    data: {
                        event: 'success',
                    }
                }
            } else {
                Taro.showToast({
                    title: '充值失败，请联系客服',
                    icon: 'none',
                });
            }
        }
    
        return {
            success: false,
            data: {
                event: 'fail',
            }
        }
    } catch (error) {
        console.log('errorerror', error)
        if (error.errMsg === 'requestPayment:fail cancel') {
            // 取消 不需要处理
            Taro.hideLoading();
            return {
                success: true,
                data: {
                    event: 'cancel',
                }
            }
        }
    }
     
}